package com.util;
import com.config.RestTemplateConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Import;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import io.fabric8.kubernetes.client.RequestConfig;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.Map;

@Service
@EnableAutoConfiguration
@Import(value={RestTemplateConfig.class})
public class TokenRequest{

    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(com.util.TokenRequest.class);

    public String getToken() throws Exception {
        {
            RestTemplate client = new RestTemplate();
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
            String requestJson = "{\n" +
                    "\t\"auth\": {\n" +
                    "\t\t\"identity\": {\n" +
                    "\t\t\t\"methods\": [\n" +
                    "\t\t\t\t\"password\"\n" +
                    "\t\t\t],\n" +
                    "\t\t\t\"password\": {\n" +
                    "\t\t\t\t\"user\": {\n" +
                    "\t\t\t\t\t\"name\": \"cangoitadmin\",\n" +
                    "\t\t\t\t\t\"password\": \"op17afv71$n\",\n" +
                    "\t\t\t\t\t\"domain\": {\n" +
                    "\t\t\t\t\t\t\"name\": \"cangoitadmin\"\n" +
                    "\t\t\t\t\t}\n" +
                    "\t\t\t\t}\n" +
                    "\t\t\t}\n" +
                    "\t\t},\n" +
                    "\t\t\"scope\": {\n" +
                    "\t\t\t\"project\": {\n" +
                    "\t\t\t\t\"name\": \"cn-east-2\"\n" +
                    "\t\t\t}\n" +
                    "\t\t}\n" +
                    "\t}\n" +
                    "}";

            HttpEntity<String> entity = new HttpEntity<String>(requestJson,headers);
            HttpEntity<String> response = client.exchange(
                    "https://iam.cn-east-2.myhuaweicloud.com/v3/auth/tokens", HttpMethod.POST, entity, String.class);
            return response.getHeaders().getFirst("X-Subject-Token");
        }
    }

}
